import Layout from "@/layout";
import {getUserMenu} from "@/api/user";
import router from "@/router";
import routePath from "@/router/routePath";
import constantRoutes from "@/router/constantRoutes";
import errorRoutes from "@/router/errorRouter";
import exampleRouter from "@/router/exampleRouter";
import {isDev} from "@/config";

const state = {
	routes: []
}

const mutations = {
	SET_ROUTES: (state, routes) => {
		state.routes = routes
		
	}
}

const actions = {
	async generateRoutes({commit}, menus) {
		const generateMenuTree = (data, parentId) => {
			return data.reduce((tree, menu) => {
				if (menu.parentId === parentId) {
					
					const children = generateMenuTree(data, menu.id);
					if (children.length > 0) {
						menu.children = children;
					}
					tree.push(menu);
				}
				if (menu.parentId === -1) {
					menu.component = Layout
				} else {
					menu.component = routePath[menu.componentPath]
				}
				menu.name = menu.menuName
				menu.meta.title = menu.menuName
				menu.meta.icon = menu.menuIcon
				return tree;
			}, []);
		};
		
		const {data, code} = await getUserMenu()
		if (code === 200) {
			const asyncRouter = generateMenuTree(data, -1)
			let routeAll = [...constantRoutes, ...asyncRouter, ...errorRoutes]
			if (isDev) routeAll = routeAll.concat(exampleRouter)
			commit('SET_ROUTES', routeAll)
			router.addRoutes(routeAll)
		}
	},
	resetRoutes({commit}) {
		return new Promise(resolve => {
			commit('SET_ROUTES', [])
			resolve()
		})
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}
